/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.yuns.aspect;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.yuns.exception.MyException;
import com.yuns.jwt.JWTUtil;
import com.yuns.model.entity.SysLogin;
import com.yuns.model.entity.SysUser;
import com.yuns.model.service.SysLoginService;
import com.yuns.util.HttpContextUtil;
import com.yuns.util.IpUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 系统日志，切面处理类
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {
	@Autowired
	private SysLoginService sysLoginService;

	private String errorMsg = "正常";
	private int state = 200;

	@Pointcut("within(@org.springframework.stereotype.Repository *)" +
			" || within(@org.springframework.stereotype.Service *)" +
			" || within(@org.springframework.web.bind.annotation.RestController *)")
	public void innerPointcut() {
		// Method is empty as this is just a Pointcut, the implementations are in the advices.
	}

//
//	@Pointcut("within(@com.yuns.aspect.SyslogAnno *)")
//	public void innerPointcut() {
//		// Method is empty as this is just a Pointcut, the implementations are in the advices.
//	}


//		@Pointcut("execution(* org.luwenchao.web.controller.*.*(..))")
	@Pointcut("within(com.yuns.web.controller..*) || within(com.yuns.shiro..*)|| within(com.yuns.jwt..*)")
	public void logPointCut() {
	}

	@Around("innerPointcut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		log.info("进入 log ................................");
		long beginTime = System.currentTimeMillis();
		Object result = null;
		try{
			//执行方法
			result = point.proceed();
		}catch (Exception e){
			state = 500;
			errorMsg = e.getMessage();
			 e.printStackTrace();
			throw new MyException(e.getMessage(),500);
		}finally {
			//执行时长(毫秒)
			long time = System.currentTimeMillis() - beginTime;
			//保存日志
			saveSysLog(point, time);
		}
		return result;
	}

	private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {

		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		SyslogAnno syslogAnno = method.getAnnotation(SyslogAnno.class);
		if (syslogAnno==null){
			return;
		}
		//请求的参数
		String[] paramNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
		log.info(paramNames.length + "....................长度");
		Object[] args = joinPoint.getArgs();
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < args.length; i++){
			sb.append(args[i]);
		}
		//获取request
		HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
		//设置IP地址
		String ip = request.getRemoteAddr();
		SysLogin sysLog = new SysLogin();
		//用户名
		String name = null;
		SysUser user = JWTUtil.getUser();
		if(user!=null){
			sysLog.setCreatedBy(user.getUserName());
		}
		sysLog.setParams(JSONObject.toJSONString(sb));
		sysLog.setIpAddr(ip);
			//注解上的描述
			sysLog.setOperation(syslogAnno.value());
		sysLog.setTimes(time);
		sysLog.setStatus(state);
		sysLog.setCreateTime(new Date());
		sysLog.setError(errorMsg);
		sysLog.setPayload(methodName);
        sysLoginService.insert(sysLog);
	}

}
